package com.wxh.jwt.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wxh.jwt.annotation.PassToken;
import com.wxh.jwt.annotation.UserLoginToken;
import com.wxh.jwt.model.User;
import com.wxh.jwt.service.UserService;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @ClassName: AuthenticationInterceptor
 * @Description: 认证拦截器实现spring的HandlerInterceptor
 * @Author wxh
 * @Date: 2020/5/28 11:10
 * @Version V1.0.0
 * @Since 1.8
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Resource
    private UserService userService;

    /**
     * 请求处理之前，使用该接口，比如登录拦截，请求参数中增加参数，记录日志等等
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 不是处理方法实例，直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 检查是否有passToken注解，有则跳过认证
        if(method.isAnnotationPresent(PassToken.class)){
            PassToken passToken = method.getAnnotation(PassToken.class);
            if(passToken.required()){
                return true;
            }
        }
        // 检查是否用户登录UserLoginToken注解
        if(method.isAnnotationPresent(UserLoginToken.class)){
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if(userLoginToken.required()){
                // 认证token
                // 1. 判断token是否为空
                if(token == null){
                    throw new RuntimeException("token为空，请重新登录！");
                }
                // 2. 获取token中userId
                String userId = null;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException e) {
                    throw new RuntimeException("用户无访问权限！");
                }
                User user = userService.findUserByUserId(userId);
                if(user == null){
                    throw new RuntimeException("该用户不存在，请重新登录！");
                }
                // 3.验证token真实性
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("用户无访问权限！");
                }
                return true;
            }
        }
        return true;
    }

    /**
     * 请求处理完后，页面还没有渲染，
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    /**
     *  请求处理完，页面渲染完后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
